/*---------- overlayfs.c ----------*/
#include "vfs.h"

// typedef struct {
//     vfs_filesystem_t* upper;
//     vfs_filesystem_t* lower;
//     uint8_t*          write_log;  // 修改日志
// } overlayfs_private_t;

ssize_t overlay_write(vfs_inode_t* inode, const void* buf, size_t size, off_t offset) {
    vfs_filesystem_t* fs = (vfs_filesystem_t*)inode->i_private;
    overlayfs_private_t* priv = (overlayfs_private_t*)fs->fs_private;
    
    // 所有写操作定向到upper层
    vfs_inode_t upper_inode = {
        .i_private = priv->upper,
        .i_cluster = inode->i_cluster
    };
    
    // 写入upper层
    ssize_t ret = priv->upper->ops.write(&upper_inode, buf, size, offset);
    
    // 记录修改日志（示例：在内存中记录偏移量）
    uint32_t log_entry = (offset << 16) | size;
    memcpy(fs->base_addr + priv->write_log, &log_entry, sizeof(log_entry));
    
    return ret;
}

ssize_t overlay_read(vfs_inode_t* inode, void* buf, size_t size, off_t offset) {
    overlayfs_private_t* priv = (overlayfs_private_t*)fs->fs_private;
    
    // 1. 检查upper层是否有数据
    vfs_inode_t upper_inode = {.i_private = priv->upper};
    ssize_t ret = priv->upper->ops.read(&upper_inode, buf, size, offset);
    
    // 2. 如果upper层没有，读取lower层
    if (ret <= 0) {
        vfs_inode_t lower_inode = {.i_private = priv->lower};
        ret = priv->lower->ops.read(&lower_inode, buf, size, offset);
    }
    
    // 3. 应用修改日志（示例实现）
    uint32_t log_entry;
    memcpy(&log_entry, priv->write_log + fs->base_addr, sizeof(log_entry));
    if (log_entry != 0) {
        uint32_t log_offset = log_entry >> 16;
        uint32_t log_size = log_entry & 0xFFFF;
        memcpy(buf + log_offset, priv->upper->base_addr + log_offset, log_size);
    }
    
    return ret;
}

int overlay_init(vfs_filesystem_t* fs) {
    overlayfs_private_t* priv = kmalloc(sizeof(overlayfs_private_t));
    priv->write_log = fs->base_addr; // 使用镜像前4KB作为日志区
    fs->fs_private = priv;
    return 0;
}